package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cskaoyan.wordmemorize.converter.VocBookConverter;
import com.cskaoyan.wordmemorize.dao.entity.VocBookDO;
import com.cskaoyan.wordmemorize.dao.mapper.VocBookMapper;
import com.cskaoyan.wordmemorize.dto.admin.DeleteBookOperateDTO;
import com.cskaoyan.wordmemorize.common.annotation.OperateLog;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.admin.VocBookDTO;
import com.cskaoyan.wordmemorize.request.BatchDeleteCommand;
import com.cskaoyan.wordmemorize.request.VocBookCommand;
import com.cskaoyan.wordmemorize.request.VocBookPageRequest;
import com.cskaoyan.wordmemorize.service.VocBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 单词书籍服务实现类
 */
@Service
public class VocBookServiceImpl extends ServiceImpl<VocBookMapper, VocBookDO> implements VocBookService {

    @Autowired
    private VocBookConverter vocBookConverter;


    /**
     * 分页展示单词书籍(后端-物料管理-书籍管理)
     *
     * @param pageQuery 分页查询条件
     * @return 分页结果
     */
    @Override
    public PageDTO<VocBookDTO> getBookPage(VocBookPageRequest pageQuery) {
        // 构建查询条件
        LambdaQueryWrapper<VocBookDO> queryWrapper = new LambdaQueryWrapper<>();

        // 如果有类目ID，按类目ID查询
        if (StringUtils.hasText(pageQuery.getCategoryId())) {
            queryWrapper.eq(VocBookDO::getBcId, Long.parseLong(pageQuery.getCategoryId()));
        }

        // 如果有关键词，则添加模糊查询条件——书籍名称
        if (StringUtils.hasText(pageQuery.getKeyword())) {
            queryWrapper.and(wrapper ->
                    wrapper.like(VocBookDO::getName, pageQuery.getKeyword())
            );
        }


        // 按排序字段排序
        queryWrapper.orderByAsc(VocBookDO::getSortBy);

        // 执行分页查询
        Page<VocBookDO> page = new Page<>(
                pageQuery.getPageNum() != null ? pageQuery.getPageNum() : 1,
                pageQuery.getCount() != null ? pageQuery.getCount() : 10
        );

        Page<VocBookDO> resultPage = this.page(page, queryWrapper);

        // 使用转换器将查询结果转换为分页DTO
        return vocBookConverter.vocBookList2Page(resultPage.getRecords(), resultPage.getTotal());
    }


    /**
     * 添加单词书籍(后端-物料管理-书籍管理)
     *
     * @param command 书籍请求体对象
     * @return 新增书籍的ID
     */
    @Override
    @Transactional
    @OperateLog(dateType = "书籍", operateType = 1)
    public Long addVocBook(VocBookCommand command) {
        // 将请求体对象转换为实体对象
        VocBookDO vocBookDO = vocBookConverter.vocBookCommand2VocBookDO(command);

        // 设置章节数量初始值
        vocBookDO.setChapterCount(0);

        // 保存实体对象
        this.save(vocBookDO);

        // 返回新增书籍的ID
        return vocBookDO.getId();
    }

    /**
     * 更新单词书籍(后端-物料管理-书籍管理)
     *
     * @param command 书籍请求体对象
     */
    @Override
    @Transactional
    @OperateLog(dateType = "书籍", operateType = 2)
    public void updateVocBook(VocBookCommand command) {
        // 检查书籍是否存在
        if (StringUtils.hasText(command.getId())) {
            VocBookDO vocBookDO = this.getById(Long.parseLong(command.getId()));
            if (vocBookDO != null) {
                // 将请求体对象转换为实体对象
                VocBookDO updateVocBookDO = vocBookConverter.vocBookCommand2VocBookDO(command);
                updateVocBookDO.setId(Long.parseLong(command.getId()));

                // 保留原有的章节数量
                updateVocBookDO.setChapterCount(vocBookDO.getChapterCount());

                // 更新实体对象
                this.updateById(updateVocBookDO);
            }
        }
    }

    /**
     * 删除单词书籍(后端-物料管理-书籍管理)
     *
     * @param bookId 书籍ID
     * @return 删除操作日志信息
     */
    @Override
    @Transactional
    @OperateLog(dateType = "书籍", operateType = 3)
    public DeleteBookOperateDTO deleteVocBook(Long bookId) {
        // 查询要删除的书籍
        VocBookDO vocBookDO = this.getById(bookId);
        if (vocBookDO == null) {
            return null;
        }

        // 逻辑删除书籍
        this.removeById(bookId);

        // 转换为操作日志DTO并返回
        return vocBookConverter.vocBookDO2DeleteBookDTO(vocBookDO);
    }

    /**
     * 批量删除选中的单词书籍(后端-物料管理-书籍管理)
     *
     * @param command 批量删除请求体对象
     * @return 操作日志列表
     */
    @Override
    @Transactional
    @OperateLog(dateType = "书籍", operateType = 4)
    public List<DeleteBookOperateDTO> deleteVocBooks(BatchDeleteCommand command) {
        if (command.getIds() == null || command.getIds().isEmpty()) {
            return new ArrayList<>();
        }

        // 将字符串ID转换为Long类型
        List<Long> bookIds = command.getIds().stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());

        // 查询要删除的书籍
        List<VocBookDO> vocBookDOList = this.listByIds(bookIds);
        if (vocBookDOList.isEmpty()) {
            return new ArrayList<>();
        }

        // 批量删除书籍
        this.removeByIds(bookIds);

        // 转换为操作日志DTO列表并返回
        return vocBookConverter.vocBookDOs2DeleteBookDTOs(vocBookDOList);
    }
}
